package com.jeasonzhao.report.decorator;

import com.jeasonzhao.report.dataset.DataSet;
import com.jeasonzhao.report.engine.irp.IDataSetDecorator;
import com.jeasonzhao.report.exceptions.DecoratorException;
import com.jeasonzhao.report.model.Report;

public class AppendInfoDecorator implements IDataSetDecorator
{
    private static volatile  AppendInfoDecorator m_instance = null;
    public static AppendInfoDecorator getInstance()
    {
        if(null == m_instance)
        {
            synchronized(AppendInfoDecorator.class)
            {
                m_instance = new AppendInfoDecorator();
            }
        }
        return m_instance;
    }

    private AppendInfoDecorator()
    {
        super();
    }

    public DataSet decorate(Report report,DataSet dataset)
        throws DecoratorException
    {
        if(null == report || null == dataset)
        {
            return dataset;
        }
        for(int n = 0;null != report.getDecorators() && n < report.getDecorators().size();n++)
        {
            String strClassName = report.getDecorators().get(n);
            if(null == strClassName || strClassName.trim().length() < 1)
            {
                continue;
            }
            //log.debug(report + " 加载处理类 " + strClassName + "....");
            try
            {
                Class<?> cls = Class.forName(strClassName);
                if(IDataSetDecorator.class.isAssignableFrom(cls) == false)
                {
                    throw new DecoratorException.CastError(report,strClassName,IDataSetDecorator.class);
                }
                IDataSetDecorator provider = (IDataSetDecorator) cls.newInstance();
                dataset = provider.decorate(report,dataset);
            }
            catch(ClassNotFoundException ex)
            {
                throw new DecoratorException.ClassNotFound(report,strClassName,ex);
            }
            catch(IllegalAccessException ex)
            {
                throw new DecoratorException.CastError(report,strClassName,IDataSetDecorator.class,ex);
            }
            catch(InstantiationException ex)
            {
                throw new DecoratorException.CastError(report,strClassName,IDataSetDecorator.class,ex);
            }
        }
        return dataset;
    }

}
